package com.example.administrator.jingpingou.login;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.query.Select;
import com.example.administrator.jingpingou.R;
import com.example.administrator.jingpingou.activity.RegisterActivity;
import com.example.administrator.jingpingou.activity.WebTaoActivity;
import com.example.administrator.jingpingou.application.MyApplication;
import com.example.administrator.jingpingou.bean.LoginUserBean;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.Event;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import de.greenrobot.event.EventBus;

public class LoginActivity extends AppCompatActivity implements PlatformActionListener {

    private RadioGroup mRG;
    private ImageView mImageBack;
    private TextView mTextRegister, mTextLog;
    private EditText mEditName, mEditPwd;
    private DbManager mDb;
    private boolean isThrid;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String pwd = initPwd(8);
            Platform platform = (Platform) msg.obj;
            String userName = platform.getDb().getUserName();
            String userIcon = platform.getDb().getUserIcon();
            LoginUserBean loginUserBean = new LoginUserBean();
            loginUserBean.setName(userName);
            loginUserBean.setPassword(pwd);
//            loginUserBean.setUserIcon(userIcon);
            try {
                //保存到数据库
                mDb.save(loginUserBean);
                application = (MyApplication) getApplication();
                application.setUserBeen(loginUserBean);
                mEditName.setText(userName);
                mEditPwd.setText(pwd);
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    };
    private MyApplication application;
    ;
    private List<LoginUserBean> userBeanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        DbManager.DaoConfig config = new DbManager.DaoConfig();
        config.setDbName("UserLogin");
        mDb = x.getDb(config);
        initView();
        setListener();
    }

    private void setListener() {
        mTextRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        });

        mImageBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTextLog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                try {
//                    userBeanList = mDb.selector(LoginUserBean.class).findAll();
//                } catch (DbException e) {
//                    e.printStackTrace();
//                }
//                for (int i = 0; i <userBeanList.size() ; i++) {
//                    LoginUserBean user =userBeanList.get(i);
//                    userName = user.getName();
//                    pwd = user.getPassword();
//                }
                String userName = mEditName.getText().toString();
                String pwd = mEditPwd.getText().toString();
                if (!TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(userName)) {
                    if (isThrid) {
                        application.setFlag(true);
                        finish();
                    } else {
                        if (find(userName)) {
                            if (findPass(userName, pwd)) {
                                application = (MyApplication) getApplication();
                                application.setFlag(true);
                                LoginUserBean userBean = new LoginUserBean();
                                userBean.setName(userName);
                                userBean.setPassword(pwd);
//                                user.setUserIcon("");
                                application.setUserBeen(userBean);
                                MyApplication.setUserName(userName);

//                                EventBus.getDefault().register(this);

                                finish();
                            } else {
                                Toast.makeText(LoginActivity.this, "密码输入错误,请重新输入", Toast.LENGTH_SHORT).show();
                                mEditPwd.setText("");
                            }
                        } else {
                            Toast.makeText(LoginActivity.this, "该用户之前没有注册过,请前去注册", Toast.LENGTH_SHORT).show();
                            mEditPwd.setText("");
                            mEditName.setText("");
                        }
                    }
                } else {
                    Toast.makeText(LoginActivity.this, "您还没有登录呢", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        });
    }

    private void initView() {
        mRG = (RadioGroup) findViewById(R.id.rg_activity_login);
        mTextRegister = (TextView) findViewById(R.id.tv_activity_login_register);
        mImageBack = (ImageView) findViewById(R.id.iv_activity_login_back);
        mEditName = (EditText) findViewById(R.id.et_activity_name);
        mEditPwd = (EditText) findViewById(R.id.et_activity_pwd);
        mTextLog = (TextView) findViewById(R.id.tv_activity_login_log);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }

    public void onClick(View view) {
        if (view != null) {
            switch (view.getId()) {
                case R.id.rb_activity_login_weibo:
                    ShareSDK.initSDK(this);
                    Platform platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                    authorize(platform);
                    break;
                case R.id.rb_activity_login_weixin:
                    ShareSDK.initSDK(this);
                    Platform platform3 = ShareSDK.getPlatform(Wechat.NAME);
                    authorize(platform3);
                    break;
                case R.id.rb_activity_login_qq:
                    ShareSDK.initSDK(this);
                    Platform platform2 = ShareSDK.getPlatform(QQ.NAME);
                    authorize(platform2);
                    break;
                default:

                    break;
            }
        }
    }

    //去数据库查询看看之前注册过没有
    public boolean find(String name) {
        try {
            userBeanList = mDb.selector(LoginUserBean.class).where("Name", "=", name).findAll();
            if (userBeanList.size()>0){
                for (int i = 0; i < userBeanList.size(); i++) {
                    LoginUserBean loginUserBean = userBeanList.get(i);
                    String name1 = loginUserBean.getName();
                    if (!TextUtils.isEmpty(name1) && name.equals(name1)) {
                        return true;
                    }
                }
            }else {
                Toast.makeText(LoginActivity.this, "去注册啊亲 ", Toast.LENGTH_SHORT).show();
            }

        } catch (DbException e) {
            e.printStackTrace();
        }

        return false;
    }

    //取数据库查找注册过的用户名密码对不对
    public boolean findPass(String name, String pass) {
        try {
            List<LoginUserBean> userBeen = mDb.selector(LoginUserBean.class).where("Name", "=", name).where("password", "=", pass).findAll();
            if (userBeen != null && userBeen.size() > 0) {
                return true;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

        return false;
    }


    //授权完成
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//        platform.getDb().getUserName();
//        platform.getDb().getUserIcon();
        isThrid = true;
        if (platform != null) {
            Message msg = Message.obtain();
            msg.obj = platform;
            mHandler.sendMessage(msg);
        }

    }


//    // 是否显示密码
//    @Override
//    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        switch (buttonView.getId()) {
//            case R.id.cb_login_select:
//                if (isChecked) {
//                     mEditPwd.setInputType(EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//                } else {
//                    mEditPwd.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD
//                            | EditorInfo.TYPE_CLASS_TEXT);
//
//                }
//                break;
//
//            default:
//                break;
//        }
//
//    }

    // 随机生成一个密码
    private String initPwd(int num) {
        // TODO Auto-generated method stub
        char[] str = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
        int maxNum = 9;
        int count = 0;
        int i;
        StringBuffer pwd = new StringBuffer();
        while (count < num) {
            i = Math.abs(new Random().nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }


    private void authorize(Platform plat) {
        if (plat == null) {
            // popupOthers();
            Toast.makeText(LoginActivity.this, "平台为空", Toast.LENGTH_SHORT).show();
            return;
        }
        //判断指定平台是否已经完成授权
        if (plat.isAuthValid()) {
            String userName = plat.getDb().getUserName();
            if (userName != null) {
                //根据名字取数据库里面查找密码
                try {
                    List<LoginUserBean> userBeen = mDb.selector(LoginUserBean.class).where("Name", "=", userName).findAll();
                    if (userBeen != null) {
                        //第二次登录的时候重新给application赋值
                        MyApplication application = (MyApplication) getApplication();
                        application.setUserBeen(userBeen.get(0));

                        String pass = userBeen.get(0).getPassword();
                        mEditName.setText(userName);
                        mEditPwd.setText(pass);
                        Log.i("lpc", "pass" + pass);
                        Log.i("lpc", "userIcon" + plat.getDb().getUserIcon());
                    } else {
                        Toast.makeText(LoginActivity.this, "没找到该用户信息", Toast.LENGTH_SHORT).show();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
                return;
            }
        }
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(false);
        //获取用户资料
        plat.showUser(null);
    }
    public void onShowMessageEvent(MessageEvent messageEvent){
        messageEvent.isMessage();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public class MessageEvent{
        private boolean message;
        public MessageEvent(boolean message){
            this.message =message;
        }

        public boolean isMessage() {
            return message;
        }

        public void setMessage(boolean message) {
            this.message = message;
        }
    }
}
